package com.homework.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.homework.dto.MistakeQuestionDTO;
import com.homework.dto.MistakeSubjectDTO;
import com.homework.dto.Result;
import com.homework.entity.MistakeQuestion;
import com.homework.entity.MistakeSubject;
import com.homework.service.AuthService;
import com.homework.service.MistakeService;
import com.homework.util.PinyinUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/mistake")
@RequiredArgsConstructor
public class MistakeController {

    private final MistakeService mistakeService;

    @Autowired
    private AuthService authService;

    // 允许的图片文件类型
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            "image/jpeg", "image/jpg", "image/png", "image/gif"
    );

    // 最大文件大小：10MB
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    /**
     * 检查管理员权限
     */
    private boolean checkAdminPermission(HttpSession session) {
        try {
            Result<Boolean> result = authService.checkLoginStatus(session);
            return result.getData() != null && result.getData();
        } catch (Exception e) {
            log.warn("检查管理员权限失败", e);
            return false;
        }
    }

    /**
     * 获取所有科目
     */
    @GetMapping("/subjects")
    public Result<List<MistakeSubject>> getAllSubjects() {
        try {
            List<MistakeSubject> subjects = mistakeService.getAllSubjects();
            return Result.success(subjects);
        } catch (Exception e) {
            log.error("获取科目列表失败", e);
            return Result.error("获取科目列表失败: " + e.getMessage());
        }
    }

    /**
     * 创建科目（仅管理员）
     */
    @PostMapping("/subjects")
    public Result<MistakeSubject> createSubject(@Valid @RequestBody MistakeSubjectDTO dto, HttpSession session) {
        try {
            if (!checkAdminPermission(session)) {
                return Result.error("需要管理员权限");
            }

            MistakeSubject subject = mistakeService.createSubject(dto);
            return Result.success(subject);
        } catch (Exception e) {
            log.error("创建科目失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取错题列表
     */
    @GetMapping("/questions")
    public Result<Page<MistakeQuestion>> getQuestions(
            @RequestParam(required = false) Long subjectId,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            Page<MistakeQuestion> questions = mistakeService.getQuestions(subjectId, keyword, page, size);
            return Result.success(questions);
        } catch (Exception e) {
            log.error("获取错题列表失败", e);
            return Result.error("获取错题列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个错题详情
     */
    @GetMapping("/questions/{id}")
    public Result<MistakeQuestion> getQuestionById(@PathVariable Long id) {
        try {
            MistakeQuestion question = mistakeService.getQuestionById(id);
            return Result.success(question);
        } catch (Exception e) {
            log.error("获取错题详情失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 创建错题
     */
    @PostMapping("/questions")
    public Result<MistakeQuestion> createQuestion(@Valid @RequestBody MistakeQuestionDTO dto) {
        try {
            MistakeQuestion question = mistakeService.createQuestion(dto);
            return Result.success(question);
        } catch (Exception e) {
            log.error("创建错题失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除错题（仅管理员）
     */
    @DeleteMapping("/questions/{id}")
    public Result<String> deleteQuestion(@PathVariable Long id, HttpSession session) {
        try {
            if (!checkAdminPermission(session)) {
                return Result.error("需要管理员权限");
            }

            mistakeService.deleteQuestion(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除错题失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 上传图片
     */
    @PostMapping("/upload")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file,
                                   @RequestParam(required = false) Long subjectId) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }

            if (file.getSize() > MAX_FILE_SIZE) {
                return Result.error("文件大小不能超过10MB");
            }

            String contentType = file.getContentType();
            if (!ALLOWED_IMAGE_TYPES.contains(contentType)) {
                return Result.error("只支持JPG、PNG、GIF格式的图片");
            }

            // 获取科目名称并转换为拼音用于创建子目录
            String subjectPinyin = "unknown";
            String originalSubjectName = "未分类";
            if (subjectId != null) {
                try {
                    MistakeSubject subject = mistakeService.getSubjectById(subjectId);
                    if (subject != null && subject.getName() != null) {
                        originalSubjectName = subject.getName();
                        subjectPinyin = PinyinUtil.convertToPinyin(originalSubjectName);

                        // 如果转换失败，使用简化处理
                        if (!PinyinUtil.isValidPinyinName(subjectPinyin)) {
                            subjectPinyin = "unknown";
                            log.warn("科目拼音转换失败，使用默认目录: {} -> {}", originalSubjectName, subjectPinyin);
                        }
                    }
                } catch (Exception e) {
                    log.warn("获取科目信息失败，使用默认目录: {}", e.getMessage());
                }
            }

            // 获取JAR应用运行目录
            String appDir = System.getProperty("user.dir");

            // 创建按科目拼音分类的上传目录
            String uploadDir = appDir + File.separator + "uploads" + File.separator + "mistake-images" + File.separator + subjectPinyin + File.separator;
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名（UUID + 时间戳）
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            String timestamp = String.valueOf(System.currentTimeMillis());
            String filename = UUID.randomUUID().toString() + "_" + timestamp + extension;
            String filePath = uploadDir + filename;

            // 保存文件
            File dest = new File(filePath);
            file.transferTo(dest);

            log.info("图片上传成功: 科目={}, 拼音目录={}, 路径={}", originalSubjectName, subjectPinyin, filePath);
            // 返回相对路径，前端负责拼接完整URL
            String relativePath = "/uploads/mistake-images/" + subjectPinyin + "/" + filename;
            return Result.success(relativePath);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("图片上传异常", e);
            return Result.error("图片上传失败: " + e.getMessage());
        }
    }
}